package cn.funeralobjects.upms.controller;

import cn.funeralobjects.common.service.CommonCloudCrudService;
import cn.funeralobjects.common.service.validate.DataCheck;
import cn.funeralobjects.common.web.controller.CommonCloudCrudController;
import cn.funeralobjects.common.web.controller.converter.ModelMapper;
import cn.funeralobjects.upm.web.model.MRole;
import cn.funeralobjects.upm.web.model.VRole;
import cn.funeralobjects.upms.api.RoleApi;
import cn.funeralobjects.upms.controller.converter.RoleMapper;
import cn.funeralobjects.upms.entity.ERole;
import cn.funeralobjects.upms.model.Role;
import cn.funeralobjects.upms.service.RoleService;
import cn.funeralobjects.util.ReactorUtils;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Mono;

import javax.annotation.Resource;

/**
 * 角色的外部访问接口
 *
 * @author FuneralObjects
 * Create date: 2020/4/28 11:52 AM
 */
@RestController
@RequestMapping(name = "role", path = "/role")
public class RoleController implements RoleApi, CommonCloudCrudController<VRole, MRole, Role, ERole, Integer> {

    @Resource
    private RoleService roleService;

    @Resource
    private RoleMapper roleMapper;

    @PostMapping("/{id}/tag")
    @Override
    public Mono<Void> addRoleTag(@PathVariable Integer id,
                                 @RequestParam String tag) {
        DataCheck.hasLength(tag, "name", roleService.createDataCode("tag", tag));
        return Mono.just(id)
                .filter(roleService::isValid)
                .flatMap(ReactorUtils.thenEmpty(i -> roleService.addRoleTag(i, tag)));
    }

    @GetMapping("/anonymous")
    @Override
    public Mono<VRole> getAnonymous() {
        return Mono.defer(() -> Mono.just(roleService.getAnonymousRole()).map(this::toVo));
    }


    @Override
    public ModelMapper<MRole, Role, ERole, VRole> modelMapper() {
        return roleMapper;
    }

    @Override
    public CommonCloudCrudService<Role, ERole, Integer> commonCloudCrudService() {
        return roleService;
    }
}
